package com.fys.order.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fys.order.utils.JsonUtils;
import com.fys.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class ProductInfoMessage {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void receiveMessage(String message){
        log.info("从队列 【{}】 接收到的消息:{}", "productInfo", message);
        //转成对象
        List<ProductInfoOutput> productInfoOutputs = JsonUtils.fromJson(message,
                new TypeReference<List<ProductInfoOutput>>() {});
        //存入redis
        if(!CollectionUtils.isEmpty(productInfoOutputs)){
            for(ProductInfoOutput productInfoOutput:productInfoOutputs){
                stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
                        String.valueOf(productInfoOutput.getProductStock()));
            }
        }
    }
}
